package activity

import java.text.SimpleDateFormat
import org.springframework.dao.DataIntegrityViolationException

class EventController {
    def historyService

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }
    
    def search() {
        def results
        if (!params.max) params.max = 10
        if (!params.field && !params.txt) {
            params.field = session.field
            params.txt = session.txt
            
        } else {
            session.field = params.field
            session.txt = params.txt
        }
        if(params.field?.equals("名稱")) {
            results = Event.findAllByNameLike("%${params.txt}%", params)
        } else {
            try{
                Date d1 = new SimpleDateFormat("yyyy/MM/dd").parse(params.txt)
                results = Event.findAllByDateStartGreaterThan(d1, params)
            } catch (Exception e) {
                flash.message = '格式錯誤'
                results = []
                render(view:"list", model:[eventInstanceList: results, eventInstanceTotal: results?.size()])
                return//沒加這個，還會繼續往後跑
            }
        }
        if (results?.size() > 0) {
            flash.message = null
        } else {
            flash.message = '查無結果'
        }
        render(view:"list", model:[eventInstanceList: results, eventInstanceTotal: results?.size()])
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        if (params.sort) {
            [eventInstanceList: Event.list(params), eventInstanceTotal: Event.count()]
        } else {
            [eventInstanceList: Event.list(sort: "id", order: "desc"), eventInstanceTotal: Event.count()]
        }
    }

    def create() {
        [eventInstance: new Event(params)]
    }

    def createBySerial(Long serialId) {
        render(view:"create", model:[eventInstance: new Event(params)])
    }

    def save() {
        def eventInstance = new Event(params)
        if (!eventInstance.save(flush: true)) {
            render(view: "create", model: [eventInstance: eventInstance])
            return
        }

        def upload = request.getFile('file')
        if(!upload.empty && upload.size < 10*1024*1024)  {
            def filename = System.nanoTime() + "." + upload.originalFilename.split("\\.", 2)[1]
            def webRootDir = servletContext.getRealPath("/")
            def filePath = "/upload/${eventInstance.id}"
            def eventDir = new File(webRootDir, filePath)
            eventDir.mkdirs()
            upload.transferTo(new File(eventDir, filename))
            eventInstance.files =  filePath + "/" + filename
            eventInstance.save()
        }
        eventInstance.updateStatus()
        historyService.createHistory(eventInstance, session)
        
        flash.message = message(code: 'default.created.message', args: [message(code: 'event.label', default: 'Event'), eventInstance.id])
        redirect(action: "show", id: eventInstance.id)
    }

    def show(Long id) {
        def eventInstance = Event.get(id)
        if (!eventInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'event.label', default: 'Event'), id])
            redirect(action: "list")
            return
        }

        [eventInstance: eventInstance]
    }

    def edit(Long id) {
        def eventInstance = Event.get(id)
        if (!eventInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'event.label', default: 'Event'), id])
            redirect(action: "list")
            return
        }

        [eventInstance: eventInstance]
    }

    def update(Long id, Long version) {
        def eventInstance = Event.get(id)
        if (!eventInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'event.label', default: 'Event'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (eventInstance.version > version) {
                eventInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'event.label', default: 'Event')] as Object[],
                          "Another user has updated this Event while you were editing")
                render(view: "edit", model: [eventInstance: eventInstance])
                return
            }
        }

        eventInstance.properties = params

        if (!eventInstance.save(flush: true)) {
            render(view: "edit", model: [eventInstance: eventInstance])
            return
        }

        def upload = request.getFile('file')
        if(!upload.empty && upload.size < 10*1024*1024)  {
            def filename = System.nanoTime() + "." + upload.originalFilename.split("\\.", 2)[1]
            def webRootDir = servletContext.getRealPath("/")
            def filePath = "/upload/${eventInstance.id}"
            def eventDir = new File(webRootDir, filePath)
            eventDir.mkdirs()
            upload.transferTo(new File(eventDir, filename))
            eventInstance.files =  filePath + "/" + filename
            eventInstance.save()
        }
        
        eventInstance.updateStatus()
        historyService.updateHistory(eventInstance, session)
        
        flash.message = message(code: 'default.updated.message', args: [message(code: 'event.label', default: 'Event'), eventInstance.id])
        redirect(action: "show", id: eventInstance.id)
    }

    def delete(Long id) {
        def eventInstance = Event.get(id)
        if (!eventInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'event.label', default: 'Event'), id])
            redirect(action: "list")
            return
        }

        try {
            historyService.deleteHistory(eventInstance, session)
            def serial = eventInstance.serial
            eventInstance.delete(flush: true)
            serial.updateFields()
            serial.save()
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'event.label', default: 'Event'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'event.label', default: 'Event'), id])
            redirect(action: "show", id: id)
        }
    }
    
    def duplicate(Long id) {
        def original = Event.findById(id)
        //先行複製報名欄位
        def orgField = original.field
        def newField = null
        if (orgField) {
            newField = new Field(orgField.properties)
            newField.id = null
            newField.save()
        }
        //去除不必要的關聯屬性
        original.history = null
        original.field = null
        original.registers = null
        original.registerQty = 0
        original.checkInQty = 0
        //複製場次
        def duplicate = new Event(original.properties)
        duplicate.id = null
        duplicate.name = duplicate.name + "複製"
        duplicate.field = newField
        duplicate.save()
        original = null
        historyService.createHistory(duplicate, session)
        redirect(action: "edit", id: duplicate.id)
    }
}